package com.fjwt.gz.coupon.hkpay;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.coupon.hkpay.hkpayutil.HkApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class HkpayCouponMerchantService {

    /**
     * 海科查询代金券可用商户
     */
    public JSONObject getMerchantList(JSONObject reqJson,String authConfig) {
        String logPrefix = "【海科匹配可用商户】";
        JSONObject authConfigJson = JSONObject.parseObject(authConfig);

            try {
                log.info("{} 请求参数：reqJson={}", logPrefix, JSONUtil.toJsonStr(reqJson));
                // 检查 authConfigJson 中的键是否存在
                if (!authConfigJson.containsKey("clientKey") || !authConfigJson.containsKey("securityKey") ||
                        !authConfigJson.containsKey("address") || !authConfigJson.containsKey("service") || !authConfigJson.containsKey("version")) {
                    throw new BizException("配置信息不完整");
                }

                HkApiClient apiClient = new HkApiClient(authConfigJson.getString("clientKey"),
                        authConfigJson.getString("securityKey"), authConfigJson.getString("address"));
                HkApiClient.ApiResponse<JSONObject> response = apiClient.request(authConfigJson.getString("service"),
                        authConfigJson.getString("version"), "WECHAT_QUERY_USABLE_MERCHANTS", reqJson, JSONObject.class);

                log.info("{} 请求参数：reqJson={},请求结果：respJson={}", logPrefix, JSONUtil.toJsonStr(reqJson), JSONUtil.toJsonStr(response));

                if (response == null) {
                    log.info("{} 请求失败,返回内容为空，请求参数：reqJson={}", logPrefix, JSONUtil.toJsonStr(reqJson));
                    throw new BizException("核验失败");
                }

                if (!"0".equals(response.getCode())) {
                    log.info("{} 请求失败，请求参数：reqJson={},返回参数：{}", logPrefix, JSONUtil.toJsonStr(reqJson), JSONUtil.toJsonStr(response));
                    throw new BizException("核验失败");
                }

                if (response.getData() == null) {
                    log.info("{} 请求失败,返回data内容为空，返回参数：{}", logPrefix, JSONUtil.toJsonStr(response));
                    throw new BizException("核验失败");
                }

                log.info("{},成功返回信息：{}", logPrefix, JSONUtil.toJsonStr(response));

                return response.getData();

            } catch (Exception e) {
                log.error("海科匹配商户失败", e);
                throw new BizException("海科匹配商户失败");
            }
        }
    }

